import { onMounted, onUnmounted, ref } from 'vue';
import { ButtonPositionEnum, type SearchAreaProps } from '../types';

type SizeType = 'xs' | 'sm' | 'md' | 'lg' | 'xl';

interface useShowLengthProps {
  buttonPositionMode: SearchAreaProps['buttonPosition'];
  config: SearchAreaProps['config'];
  globalCols: SearchAreaProps['cols'];
}

export const useShowLength = ({ buttonPositionMode, config, globalCols }: useShowLengthProps) => {
  const showLength = ref(3);
  const size = ref<SizeType>('md');

  const getSize = (): SizeType => {
    const width = document.body.offsetWidth;
    if (width < 768) {
      return 'xs';
    }
    if (width < 992) {
      return 'sm';
    }
    if (width < 1200) {
      return 'md';
    }
    if (width < 1920) {
      return 'lg';
    }
    return 'xl';
  };

  const $ResizeHandler = () => {
    if (!document.hidden) {
      size.value = getSize();
      const isOut = buttonPositionMode === ButtonPositionEnum.OUT;

      // 不是直接放在外面的情况，需要将按钮的位置计算上
      let num = isOut ? 0 : ((globalCols[size.value] || globalCols.span || 0) as number);
      let index = 0;
      for (; index < config.length; index++) {
        const cols = Object.assign({}, globalCols, config[index].cols || {});
        const colValue = cols[size.value] || cols.span || 0;
        if (num + colValue <= 24) {
          num += colValue;
        } else {
          break;
        }
      }
      // 处理按钮直接占用24的情况
      if (index === 0) {
        index = 1;
      }
      showLength.value = index;
    }
  };

  $ResizeHandler();

  onMounted(() => {
    window.addEventListener('resize', $ResizeHandler);
  });

  onUnmounted(() => {
    window.removeEventListener('resize', $ResizeHandler);
  });

  return {
    size,
    showLength,
  };
};
